package com.sky.service.Impl;

import com.sky.domain.GDTest;
import com.sky.domain.Student;
import com.sky.mapper.GDTestMapper;
import com.sky.mapper.StudentMapper;
import com.sky.service.StudentService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    StudentMapper studentMapper;

    @Autowired
    GDTestMapper gdTestMapper;

    static int count = 0;

    private volatile int a = 0;
    private volatile Long maxId;
    private volatile List<String> list = new ArrayList<>();


    @Override
    public int insert(Student student) {
        return studentMapper.insert(student);
    }

    @Override
    public int deleteById(Long id) {

        return studentMapper.deleteById(id);
    }

    @Override
    public List<Student> selectByIds(List<Long> ids , String tableName) {
        return studentMapper.selectByIds(ids, tableName);
    }


    public int GDTestGetData(int count,int size) {


        //获取某个线程处理的数据列表
        List<GDTest> gdTest = gdTestMapper.getListByLimit(count*size,size);

        synchronized (this) {
            maxId++;
        }

        synchronized (this){
            list.add("hh:" + maxId + "--");
        }

        System.out.println("-------------------------------------------");
        System.out.println(maxId);
        synchronized (this) {
            a++;
        }
        System.out.println(a);
        for (GDTest test : gdTest) {
            List<Map<String, String>> maps = analysisAddress(test.getZl());
            if(CollectionUtils.isEmpty(maps)){
                continue;
            }
            System.out.println(maps);
        }

        return gdTest.size();
    }

    //解析详细地址
    private static  List<Map<String,String>> analysisAddress(String address){

        String regex;
        if (address.contains("弄")){return null;}
        if(address.contains("绥安路") && address.contains("区块") && !address.contains("绥安路绥安新天地") && !address.contains("绥安路新天地")){
            address = address.replace("绥安路", "绥安路绥安新天地");
        }
        if (address.contains("绥安路新天地")){
            address = address.replace("绥安路新天地", "绥安路绥安新天地");
        }
        if (address.contains("广德市")){//distinguish
            regex = "(?<county>[^德市]+德市)?(?<town>[^镇]+镇)?(?<street>[^路东侧]+路东侧|.+路西侧|.+路南侧|.+路北侧|.+路东|.+路西|.+路南|.+路北|.+路交汇处|.+路|.+大道东侧|.+大道南侧|.+大道北侧|.+大道西侧|.+大道|.+街)?(?<distinguish>[^幢]+幢|.+号楼|.+座|.+栋|)?(?<unit>[^单元]+单元|.+座|.+号)?(?<house>.*)";
        }  else {
            regex = "(?<county>[^县]+县|.+广德)?(?<town>[^镇]+镇)?(?<street>[^路东侧]+路东侧|.+路西侧|.+路南侧|.+路北侧|.+路东|.+路西|.+路南|.+路北|.+路交汇处|.+路|.+大道东侧|.+大道南侧|.+大道北侧|.+大道西侧|.+大道|.+街)?(?<distinguish>[^幢]+幢|.+号楼|.+座|.+栋|)?(?<unit>[^单元]+单元|.+座|.+号)?(?<house>.*)";
        }
        String regex1 = "[\\u4e00-\\u9fa5]+";
        Matcher matcher = Pattern.compile(regex).matcher(address);
        String county;
        String town;
        String house;
        String house1;
        String street;
        String unit;
        String unit1;
        List<Map<String,String>> maps = new ArrayList<>();
        Map<String,String> map;
        while (matcher.find()){
            map=new LinkedHashMap<>();
            //市/县数据
            county=matcher.group("county");
            if(county !=null && county.equals("广德县")){ county = "广德市";}
            map.put("county", county==null?"广德市":county.trim());
            //镇数据
            town=matcher.group("town");
            map.put("town", town==null?"":town.trim());
            //街道数据
            street = matcher.group("street");
            map.put("street", street == null ? "" : street.trim());
            //楼栋小区的数据
            if (matcher.group("distinguish") == null || matcher.group("distinguish").equals("")) { continue;}

            if(address.contains("团结路") && address.contains("区")){
                String regex2 = "(?<county>[^区西]+区西|.+区北|.+区南|.+区)";
                Matcher matcher3 = Pattern.compile(regex2).matcher(matcher.group("distinguish"));
                if(matcher3.find()){
                    String group1 = matcher3.group();
                    if(group1 != null){
                        group1 = verifyArea(group1);
                        if(group1 == null){continue;}
                        map.put("distinguish",street + group1.trim());
                        String distinguish = matcher.group("distinguish").replace(group1, "");
                        removeUnit(distinguish, map, regex1);
                    }
                }

            }
            else if(address.contains("横山南路西") || address.contains("横山南路东") || address.contains("横山中路") || (address.contains("团结西路") && address.contains("安置房"))
            ||(matcher.group("distinguish").charAt(0) >= 48 && matcher.group("distinguish").charAt(0) <= 59)){//处理解析后小区开头是数字的数据
                if (distinguishFix(street + matcher.group("distinguish"), map, regex1) == null){continue;}
            }
            else {
                if (distinguishFix(matcher.group("distinguish"), map, regex1) == null){continue;}
            }
            //获取单元数据
            unit = matcher.group("unit");
            if (unit != null) {
                Matcher matcher1 = Pattern.compile(regex1).matcher(unit);
                if(matcher1.find()){
                    unit1 = matcher1.group();
                    if (unit1 != null) {
                        unit = unit.replace(unit1, "");
                        map.put("unit", unit.trim());
                    }
                }
            }else {
                map.put("unit","1");
            }
            //获取房屋数据
            house = matcher.group("house");
            if (house != null && !house.equals("")) {
                if(house.contains("、") || house.contains(" ") || house.contains(".") || house.contains("-")
                        || house.contains("·") || house.contains(",") || house.contains("，")){continue;}
                //将中文去掉
                Matcher matcher1 = Pattern.compile(regex1).matcher(house);
                if(matcher1.find()){
                    house1 = matcher1.group();
                    if (house1 != null) {
                        house = house.replace(house1, "");
                        //去掉房屋号前面的0
                        if(house.equals("")){continue;}
                        if(house.charAt(0) == 48){
                            house = house.replace("0", "");
                        }
                        //排除最后一位为数字和字母以外的情况
                        if ((house.charAt(house.length() - 1) >= 65 && house.charAt(house.length() - 1) <= 90) ||
                                (house.charAt(house.length() - 1) >= 97 && house.charAt(house.length() - 1) <= 122) ||
                                (house.charAt(house.length() - 1) >= 48 && house.charAt(house.length() - 1) <= 59)) {
                            map.put("house", house.trim());
                        }else {
                            continue;
                        }
                    }
                }else {
                    map.put("house", house.trim());
                }
            }else {
                return null;
            }
            maps.add(map);
        }
        System.out.println(maps);
        return maps;
    }

    //线程导入操作
    @Override
    public void importList(){


        List<GDTest> gdTest = gdTestMapper.getAll();

        list.add("12");

        maxId = studentMapper.getMaxId();


        GDTestGetData(100000,1000);
        if (gdTest.size() > 1000) {
            int size = gdTest.size()/10 + 1;

            ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(8, 8, 5, TimeUnit.SECONDS,
                    new LinkedBlockingDeque<>(100000), new ThreadPoolExecutor.AbortPolicy());

            CountDownLatch latch = new CountDownLatch(10);
            //线程异执行
            for(int i = 0; i<10;i++){
                CompletableFuture.supplyAsync(() ->
                        this.GDTestGetData(count,size),poolExecutor
                ).thenAccept(dto -> {//获取返回结果
                    latch.countDown();
                });
//                System.out.println(count);
                count++;
            }
            try {
                latch.await(300, TimeUnit.SECONDS);
                System.out.println(list);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }else {
            GDTestGetData(0,gdTest.size());
        }
        count = 0;

    }

    /**
     * 生成自然楼栋号
     *
     * @return String
     *
     *  */
    private String createNatureNumber(Long maxId) {
        StringBuilder number = new StringBuilder();
        LocalDate date = LocalDate.now();
        String dateString = date.toString().replace("-", "");
        if(maxId == null){maxId = 1L;}
        char[] charArray = maxId.toString().toCharArray();
        number.append("LD");
        number.append(dateString);
        //超出五位数时
        if( 5 - maxId.toString().length() < 0) {
            String substring = maxId.toString().substring(maxId.toString().length() - 5);
            number.append(substring);
            return number.toString();
        }
        for (int i = 0; i < 5 - charArray.length; i++) {
            number.append(0);
        }
        //生成环境用数据库自增用1,测试环境数据库自增用2
        number.append(maxId + 2);
        return number.toString();
    }

    public static String CreateIdentifier(String number,Long id,int type){
        StringBuilder identifier = new StringBuilder();

        identifier.append(number);
        identifier.append(LocalDate.now().toString().replace("-",""));

        if(id == null){id = 1L;}

        if(type == 2){
            combination(id == 1L ? id  : id + 2, identifier);

        }else if(type == 1){
            combination(id == 1L ? id : id + 1, identifier);

        }
        return identifier.toString();

    }

    private static void combination(Long id, StringBuilder identifier) {
        //超出五位数时
        if( 5 - id.toString().length() < 0) {
            String substring = id.toString().substring(id.toString().length() - 5);
            identifier.append(substring);
            return;
        }

        for (int i = 0; i < 5 - id.toString().length(); i++) {
            identifier.append(0);
        }
        identifier.append(id);
    }

    @Override
    public Map<String, Student> getMap() {
        return gdTestMapper.getMap();
    }

    @Override
    public void test2() {
        StringBuilder name = new StringBuilder();
        List<String> list = new ArrayList<>();
        list.add("adjiwrqlvvw");
        test2_1(list);
        System.out.println(list);
        System.out.println("-------------------------------------");
        name.append("嘿嘿");
        test2_2(name);
        System.out.println(name);
    }

    @Override
    public void setKey(String sky_test, String sky) {
    }

    /**切面测试*/
    @Override
    public void AOPTest() {
        System.out.println("我zht");
    }

    private void test2_1(List<String> list) {
        list.add("asd");
    }

    private String test2_2(StringBuilder name) {
        name.append("你好呀");
        return name.toString();
    }

    /**
     * 整理小区数据
     *
     * @return String
     *
     *  */
    private static String distinguishFix(String distinguish, Map<String, String> map, String regex1){
        String distinguish1;
        //去掉符号"-"
        if(distinguish.contains("-")){
            distinguish = distinguish.replace("-", "");
        }
        //去掉符号"·"
        if(distinguish.contains("·")){
            distinguish = distinguish.replace("·", "");
        }
        //小区开头是字母
        if (distinguish.charAt(0) >= 65 && distinguish.charAt(0) <= 90) {
            Matcher matcher1 = Pattern.compile(regex1).matcher(distinguish);
            //获取区域数据,英文开头
            if(matcher1.find()){
                distinguish1 = matcher1.group();
                if (distinguish1 != null) {
                    distinguish = distinguish.replace(distinguish1, "");
                    distinguish1 = verifyArea(distinguish1);
                    map.put("distinguish", distinguish.charAt(0) + distinguish1.trim());
                    distinguish = distinguish.replace(String.valueOf(distinguish.charAt(0)), "");
                }
            }
            distinguish = removeUnit(distinguish, map, regex1);
        }else if(distinguish.contains("广德经济开发区商贸中心") && distinguish.contains("号地")){//特殊处理某一区域
            String regex2 = "(?<place>[^号地]+号地)";
            Matcher matcher2 = Pattern.compile(regex2).matcher(distinguish);
            if (matcher2.find()){
                String group = matcher2.group("place");
                if(group == null){return null;}
                //去除区域信息
                distinguish = distinguish.replace(group,"");
                group = verifyArea(group);
                map.put("distinguish", group.trim());
            }
            //去掉楼栋后面的中文单位
            distinguish = removeUnit(distinguish, map, regex1);
        }
        else if(distinguish.contains("区")){//处理区域含字母的情况
            Matcher matcher2 = Pattern.compile(regex1).matcher(distinguish);
            if (matcher2.find()){
                String group = matcher2.group();
                if(group == null){return null;}
                //将区域字母前的数据都清除
                distinguish = distinguish.replace(group,"");
                //处理A,B,C区的情况
                if(distinguish.contains("区")){
                    String regex2 = "(?<county>[^区块]+区块|.+区)";
                    Matcher matcher3 = Pattern.compile(regex2).matcher(distinguish);
                    if(matcher3.find()){
                        String group1 = matcher3.group();
                        if(group1 != null){
                            group = group + group1;
                            distinguish = distinguish.replace(group1, "");
                        }
                    }
                }
                group = verifyArea(group.trim());
                if(group != null){
                    map.put("distinguish", group.trim());
                }
            }
            //去掉楼栋后面的中文单位
            distinguish = removeUnit(distinguish, map, regex1);
        }
        else {
            Matcher matcher1 = Pattern.compile(regex1).matcher(distinguish);
            //获取区域数据,中文开头
            if(matcher1.find()){
                distinguish1 = matcher1.group();
                if(distinguish1 != null && distinguish1.equals("众盛建材市场")){
                    distinguish1 = "广德众盛建材市场";
                }
                distinguish1 = verifyArea(distinguish1 == null ? "" : distinguish1.trim());
                map.put("distinguish", distinguish1 == null ? "" : distinguish1.trim());
                if (distinguish1 != null) {
                    distinguish = distinguish.replace(distinguish1, "");
                }
            }
            //去掉楼栋后面的中文单位
            distinguish = removeUnit(distinguish, map, regex1);
            if (distinguish == null) return null;
        }
        return distinguish;
    }

    /**
     * 去掉楼栋后面的中文单位
     *
     * @return String
     *
     *  */
    private static String removeUnit(String distinguish, Map<String, String> map, String regex1) {
        String distinguish1;
        Matcher matcher2 = Pattern.compile(regex1).matcher(distinguish);
        if (matcher2.find()) {
            distinguish1 = matcher2.group();
            distinguish = distinguish.replace(distinguish1, "");
        }
        if (distinguish.equals("")) {
            return null;
        }
        //去掉楼栋数前面的0
        if (distinguish.charAt(0) == 48) {
            distinguish = distinguish.replace("0", "");
        }

        Matcher matcher3 = Pattern.compile(regex1).matcher(distinguish);
        if (matcher3.find()) {
            distinguish1 = matcher3.group();
            distinguish = distinguish.replace(distinguish1, "");
        }
        if (distinguish.equals("")) {
            return null;
        }
        map.put("building", distinguish.trim());
        return distinguish;
    }


    /**
     * 验证是否包含区域
     *
     * @return String
     *
     *  */
    private static String verifyArea(String distinguish){
        //区域字典
        String areaes = "中央乐城,橡树玫瑰园,都市庄园,水岸阳光,建材市场,团结路,迎春花园,茗桂小区,汽配中心,春江华城,团结西路安置房,港湾花园,金峰万象广场,阳光嘉园,东城盛景,丹桂苑,紫竹园小区,桂花苑,盛世滨河,田园小区,亚夏汽车城,夫子庙广场,兰馨花园,广润花园中心广场,花园新村,春风社区,新世纪广场,上海花园洋房,南门花园,尚都商贸中心,经济开发区商贸中心," +
                "金都宾馆,万桂山*,红旗小区,茗桂花园,阳光新区,牛头山,筲箕湾,隆兴花园,星汉星蓝湾,望湖佳苑," +
                    "碧桂园,城市绿苑,安华机动车检测,金峰凤麟府,绥安新天地,小学南片,荷花,凤凰城小区和凤凰新城,西关小区,尚城滨河湾," +
                "尚城江南府,广信和园,石榴清水湾,桃苑小区,尚城江南府金桂花园,桃源名都,集美商住区,广信东郡,日月山水人家,桐汭首府,时代华府,中鼎景苑,卡地亚花园,瑞园小区,东风小区集雅苑,蓝庭国际小区,新徽商公寓," +
                "天玺公馆,广兰小区,清洁桥小区,阳光家园,日月商城,金兰绿洲山庄,时代商业中心,红旗住宅小区,丹桂园,森源商贸楼," +
                "瑞祥花园,丽晶风情街,银桂花园,东晨商贸中心,东亭乡商贸中心,小东门新村,粮长河小区,中心市场,党校新村,誓节财富广场," +
                "农行干校,柏垫金政商贸城,中心农贸市场,春熙湖畔,凤凰小区,横山别墅,金兰绿州山庄,祥生观棠府,祥生花涧樾府,天誉小区,文府南苑,凤凰新城,水灌洞,香悦兰庭,祥生君麟府," +
                "金峰新城,石榴玉兰湾,香悦荣府,中梁江山誉景小区,绿地城,翰林华府,华地翡翠小区,尚城馨苑,今创文澜府,梧桐茗院,道康庄小区";

        String[] areaList = areaes.split(",");


        if(Arrays.stream(areaList).filter(distinguish::contains).collect(Collectors.joining()).equals("荷花")){
            return "荷花社区";
        }
        return Arrays.stream(areaList).filter(distinguish::contains).collect(Collectors.joining());
    }
}




